import { Component, OnInit } from '@angular/core';
import { NavController, AlertController } from '@ionic/angular';
import { Storage } from '@ionic/storage';
import { Router } from '@angular/router';
import { EventService } from 'src/app/service/event.service';
import { ToolService } from 'src/app/service/tool.service';
import { HttpService } from 'src/app/service/http.service';
import { UrlService } from 'src/app/service/url.service';
import { ConfigService } from 'src/app/service/config.service';
import { PopwinService } from 'src/app/service/popwin.service';


@Component({
  selector: 'app-withdraw',
  templateUrl: './withdraw.page.html',
  styleUrls: ['./withdraw.page.scss'],
})
export class WithdrawPage implements OnInit {
  public money:any;
  public cardStr:any;
  public balanceNum;
  public minoutcash;
  constructor(private navCtrl:NavController,private store:Storage,private router:Router,private eventS:EventService,private http:HttpService,private popWin:PopwinService,private alertController:AlertController) { }

  ngOnInit() {
    this.initEvent();
    this.getCard();
    this.getBlanceNet();
  }

  initEvent(){
    let that=this;
      this.eventS.subscribe("selectCard",function(){
          that.getCard();
      },true);
  }
  
  getBlanceNet(){
    let that=this;
    this.http.get(UrlService.USER_SHOWACCTOUT, { "callback": "JSONP_CALLBACK" }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      if (data.code == ConfigService.SUCCESS_CODE) {
        let res = ToolService.aesDecodeToJson(data.data);
        that.balanceNum=res.balance;
        that.minoutcash=res.minoutcash;
      } else if (data.code == ConfigService.FAIL_CODE) {
        that.popWin.toast(data.message);
      } else if (data.code == ConfigService.LOGIN_CODE) {
        that.navCtrl.navigateForward("/login");
      }
    }, error => {
      console.log("error", error);
    });
  }
  /**
   * 获取缓存的用户银行卡
   */
  getCard(){
    let that=this;
    that.store.get("card").then((data)=>{
      if(!ToolService.isEmpty(data)){
        that.cardStr=data;
        console.log("-返回",that.cardStr);
      }
  });
  }
  //进六个月的体现记录
  withdrawList(){
    let param = "{\"name\":\"提现\",\"type\":\"2\"}";
    this.router.navigate(['/transaction'], {
      queryParams: { "p": ToolService.paramAESEncrypt(param)}
    });
  }

  /**
   * 提现申请
   */
  submitWithdraw(){
    if(ToolService.isEmpty(this.cardStr)){
        this.popWin.toast("请选择银行卡");
        return;
    }
    if(ToolService.keepTwoDecimal(this.money) <this.minoutcash){
      this.popWin.toast("提款金额不能低于最低提现金额");
      return;
    }
    this.presentAlertPrompt();
  }
  /**
   * 弹出支付的输入框
   */
  async presentAlertPrompt() {
    let that=this;
    const alert = await this.alertController.create({
      header: '输入支付密码',
      inputs: [
        {
          name: 'psw',
          type: 'password',
          placeholder: '输入提现密码'
        }
      ],
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          handler: () => {
           
          }
        }, {
          text: '确认',
          handler: (data) => {
            that.applyMoney(that.cardStr.bank_id,ToolService.keepTwoDecimal(this.money),data.psw);
            return false;
          }
        }
      ]
    });
    await alert.present();
  }
  /**
   * 申请提现的操作
   * @param bank_id 银行卡id
   * @param cash 提现的金额
   * @param password2 提现密码
   */
  applyMoney(bank_id,cash,password2){
    let that=this;
    let obj = "{\"bank_id\":\"" + bank_id + "\",\"out\":\{\"cash\":\""+cash+"\",\"password2\":\""+password2+"\"}\}";  
    this.http.get(UrlService.USER_USEROUTCASH, { "callback": "JSONP_CALLBACK", "data": ToolService.aesEncode(obj)  }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      if (data.code == ConfigService.SUCCESS_CODE) {
        let res = ToolService.aesDecodeToJson(data.data);
        if(res.status=='success'){
          that.backClick();
          that.storeWithdraw();
          that.alertController.dismiss();
        }
        that.popWin.toast(data.message);
      } else if (data.code == ConfigService.FAIL_CODE) {
        that.popWin.toast(data.message);
      } else if (data.code == ConfigService.LOGIN_CODE) {
        that.navCtrl.navigateForward("/login");
      }
      console.log("提现处理:",data.message);
    }, error => {
      console.log("error", error);
    });
  }

  storeWithdraw(){
    let that=this;
    this.http.get(UrlService.USER_FINDCREDIT, { "callback": "JSONP_CALLBACK" }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      if (data.code == ConfigService.SUCCESS_CODE) {
        let res = ToolService.aesDecodeToJson(data.data);
        that.store.set(ConfigService.MONEY_KEY, res);
      } else if (data.code == ConfigService.FAIL_CODE) {
        that.popWin.toast(data.message);
      } else if (data.code == ConfigService.LOGIN_CODE) {
        that.navCtrl.navigateForward("/login");
      }
    }, error => {
      console.log("error", error);
    });
  }

  backClick(){
      this.store.remove("card");
      this.navCtrl.navigateBack("/tabs/recharge");
      this.eventS.publish("updateTotalMoney");
  }
  /**
   * 选择银行卡
   */
  selectBankCard(){
    let param = "{\"s\":\"1\"}";
    this.router.navigate(['/banklist'],{
       queryParams:{ "p": ToolService.paramAESEncrypt(param)}
    });
  }

  hideName(val:String){
   return "**"+val.substr(-1,1);
  }
  /**
   * 提取所有可提金额
   */
  onWithdraw(){
    this.money=parseInt(this.balanceNum);
  }

  getBackgroundColor(){
    return 'red';
  }

}
